<?php

namespace app\admin\command;

use think\Log;
use think\console\Input;
use WanlPay\Supports\Str;
use think\console\Output;
use WanlPay\Yansongda\Pay;
use think\console\Command;
use app\admin\model\wanlshop\Order;
use app\admin\model\wanlshop\Agent;
use app\admin\model\wanlshop\AgentOrder;
use app\admin\model\wanlshop\ShareOrder;

class Queryf extends Command
{
    protected function configure()
    {
        $this->setName('queryf')
            ->setDescription('分销订单打款');
    }

    protected function execute(Input $input, Output $output)
    {
        bcscale(2);
        $redis = \addons\wanlshop\library\WanlSdk\Common::redis();
//        $redis->lPush('share_order', 3);
        $orders = Order::where([
            'is_share_order' => 1,
            'finish_share' => 0
        ])->order('id', 'desc')->select();
        $msg = '分销订单，数量:' . count($orders);
        Log::log($msg);
        $output->writeln($msg);
        if ($orders) {
            foreach ($orders as $value) {
                $msg = 'id:' . $value['id'];
                Log::log($msg);
                $output->writeln($msg);
                $shareOrders = ShareOrder::where('order_id', $value['id'])->order('id', 'desc')->select();
                foreach ($shareOrders as $item) {
                    $order = ShareOrder::find($item['id']);
                    if ($order['status'] == 1) {
                        $msg = "order continue->{$order['id']}";
                        Log::log($msg);
                        $output->writeln($msg);
                        continue;
                    }
                    $data = [
                        'out_biz_no' => $item['order_sn']
                    ];
                    $msg = 'out_trade_no:' . $item['order_sn'];
                    Log::log($msg);
                    $output->writeln($msg);
                    try {
                        $res = Pay::alipay(self::getConfig())->find($data, 'transfer');
                        var_dump($res);
                        Log::log($res);

                        Log::log('res:' . json_encode($res, 256));
                        $output->writeln('res:' . json_encode($res, 256));
                        if (!empty($res['code']) && $res['code'] == 10000 && !empty($res['msg']) && $res['msg'] == 'Success'
                            && !empty($res['status']) && $res['status'] == 'SUCCESS') {
                            $share = \app\admin\model\wanlshop\Share::withTrashed()->find($order['parent_share_id']);
                            $share->waitting = bcsub($share->waitting, $order['parent_amount']);
                            $share->amount = bcadd($share->amount, $order['parent_amount']);
                            $share->save();

                            $order->status = 1;
                            $order->pay_at = date('Y-m-d H:i:s');
                            $order->transaction_id = $res['order_id'];
                            $order->save();

                            Log::log("order udpate");
                            $output->writeln("order udpate");
                        } else {
                            Log::log("query error:" . $item['id']);
                            $output->writeln("query error:" . $item['id']);
                        }
                    } catch (\Exception $e) {
                        $output->writeln('exception:' . $e->getMessage());
                    }
                }
                Order::where('id', $value['id'])->update(['finish_share' => 1]);
                Log::log('finish_share');
                $output->writeln('finish_share');
            }
        }

        $orders = Order::where([
            'is_agent_order' => 1,
            'finish_agent' => 0
        ])->order('id', 'desc')->select();
        Log::log('代理商订单，数量:' . count($orders));
        $output->writeln('代理商订单，数量:' . count($orders));
        if ($orders) {
            foreach ($orders as $value) {
                $agentOrder = AgentOrder::where('order_id', $value['id'])->select();
                Log::log("base_order_id:{$value['id']}");
                $output->writeln("base_order_id:{$value['id']}");
                foreach ($agentOrder as $item) {
                    $order = AgentOrder::find($item['id']);
                    Log::log("agent_order_id:{$item['id']}");
                    $output->writeln("agent_order_id:{$item['id']}");
                    if ($order['status'] == 1) {
                        Log::log("order continue->{$order['id']}");
                        $output->writeln("order continue->{$order['id']}");
                        continue;
                    }
                    $data = [
                        'out_biz_no' => $item['order_sn']
                    ];
                    Log::log('out_trade_no:' . $item['order_sn']);
                    $output->writeln('out_trade_no:' . $item['order_sn']);
                    $res = Pay::alipay(self::getConfig())->find($data, 'transfer');
                    Log::log('//--------------------------------------------------');
                    var_dump($res);
                    Log::log('//--------------------------------------------------');
                    Log::log($res->toArray());
                    if (!empty($res['code']) && $res['code'] == 10000 && !empty($res['msg']) && $res['msg'] == 'Success'
                        && !empty($res['status']) && $res['status'] == 'SUCCESS') {
                        $agent = Agent::withTrashed()->find($order['parent_agent_id']);
                        if ($agent) {
                            $agent->waitting = bcsub($agent->waitting, $order['parent_amount']);
                            $agent->amount = bcadd($agent->amount, $order['parent_amount']);
                            $agent->save();
                            Log::log('agent update');
                            $output->writeln('agent update');
                        }

                        $order->status = 1;
                        $order->pay_at = date('Y-m-d H:i:s');
                        $order->transaction_id = $res['order_id'];
                        $order->save();
                        Log::log('agentOrder update');
                        $output->writeln('agentOrder update');
                    } else {
                        Log::log("query error:" . $item['id']);
                        $output->writeln("query error:" . $item['id']);
                    }
                    Log::log('res:' . json_encode($res, 256));
                    $output->writeln('res:' . json_encode($res, 256));
                }
                Order::where('id', $orders[0]['order_id'])->update(['finish_agent' => 1]);
                Log::log('finish_agent');
                $output->writeln('finish_agent');
            }
        }
    }

    private function getConfig()
    {
        $config = get_addon_config('wanlshop');
        $pay_config = [
            'app_id' => $config['sdk_alipay']['app_id'],
            'notify_url' => 'https://donghuomu.jiuhuanmall.com/api/callback',
            //'return_url' => $config['ini']['appurl'] . $config['sdk_alipay']['return_url'],
            'private_key' => $config['sdk_alipay']['private_key'],
            'log' => [
                'file' => LOG_PATH . 'wanlpay' . DS . 'alipay' . '-' . date("Y-m-d") . '.log',
                'level' => 'info', // todo 建议生产环境等级调整为 info，开发环境为 debug
                'type' => 'single', // optional, 可选 daily.
                'max_file' => 30, // optional, 当 type 为 daily 时有效，默认 30 天
            ],
            'http' => [
                'timeout' => 5.0,
                'connect_timeout' => 5.0
            ],
        ];
        if (isset($config['sdk_alipay']['app_cert_public_key']) && substr($config['sdk_alipay']['app_cert_public_key'], 0, 8) == '/addons/') {
            $pay_config['app_cert_public_key'] = ROOT_PATH . str_replace('/', DS, substr($config['sdk_alipay']['app_cert_public_key'], 1));
        }
        if (isset($config['sdk_alipay']['alipay_root_cert']) && substr($config['sdk_alipay']['alipay_root_cert'], 0, 8) == '/addons/') {
            $pay_config['alipay_root_cert'] = ROOT_PATH . str_replace('/', DS, substr($config['sdk_alipay']['alipay_root_cert'], 1));
        }
        if (isset($config['sdk_alipay']['ali_public_key']) && (Str::endsWith($config['sdk_alipay']['ali_public_key'], '.crt') || Str::endsWith($config['sdk_alipay']['ali_public_key'], '.pem'))) {
            $pay_config['ali_public_key'] = ROOT_PATH . str_replace('/', DS, substr($config['sdk_alipay']['ali_public_key'], 1));
        }
        return $pay_config;
    }
}